#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/14 10:39
# @Author  : 王凯
# @File    : chongqing_illegal.py
# @Project : spider-man
import datetime
import re

from apps.tax_illegal.tax_illegal.items import NetTaxIllegalProItem
from apps.tax_illegal.tax_illegal.spiders import BaseTaxIllegalSpider


class ChongqingIllegalSpider(BaseTaxIllegalSpider):
    name: str = "chongqing_illegal"
    province: str = "重庆"
    url: str = "http://chongqing.chinatax.gov.cn/xxgkxt/pages/qywh/zdwfajcx.html"  # 取首页

    def start_requests(self):
        yield from self.etax_search(**{"etax_url": "https://etax.chongqing.chinatax.gov.cn:8443"})
        url = "http://chongqing.chinatax.gov.cn/api/qeuryZdaj"
        for year in range(2017, datetime.datetime.now().year + 1):
            data = {"jsonstr": '{"pageSize":"10","pageIndex":"1","nd":"' + f"{year}" + '"}'}
            yield self.FormRequest(url, method="POST", formdata=data, cb_kwargs=dict(year=year))

    def parse(self, response, **kwargs):
        url = "http://chongqing.chinatax.gov.cn/api/qeuryZdaj"
        yield from self.parse_list(response, **kwargs)
        total = int(response.json()["total"] or 1)
        current_page = kwargs.get("current_page", 1)
        if current_page < total // 10 + 1:
            current_page = current_page + 1
            data = {
                "jsonstr": '{"pageSize":"10","pageIndex":"'
                + f"{current_page}"
                + '","nd":"'
                + f"{kwargs.get('year')}"
                + '"}'
            }
            yield self.FormRequest(url, method="POST", formdata=data, cb_kwargs=dict(year=kwargs.get("year"), current_page=current_page))

    def parse_list(self, response, **kwargs):
        datas = response.json().get("data", []) or []
        url = "http://chongqing.chinatax.gov.cn/api/queryZdajById"
        for data in datas:
            data = {"id": data["id"]}
            yield self.FormRequest(url, method="POST", formdata=data, callback=self.parse_detail)

    def parse_detail(self, response, **kwargs):
        item = NetTaxIllegalProItem()
        info = response.json().get("value", {})
        mapping = {
            "nsrmc": "company_name",
            "nsrsbh": "taxpayer_id",
            "zzjgdm": "org_code",
            "zcdz": "address",
            # "ajxz": "illegal_status",
            "wfxx": "illegal_facts",
            "legalBasis": "basis_and_punishment",
        }

        for k, v in info.items():
            if mapping.get(k):
                setattr(item, mapping.get(k), v)

        if info.get("frxm"):
            item.legal_representative = "法定代表人或者负责人姓名：{}；性别：{}；证件号码：{}".format(
                info.get("frxm", ""), info.get("frxb", ""), info.get("frzjhm", "")
            )

        if info.get("ajxz"):
            item.illegal_status = (
                info.get("ajxz", "")
                .replace(",", ";")
                .replace("1", "偷税")
                .replace("2", "逃避追缴欠税")
                .replace("3", "骗取出口退税")
                .replace("4", "抗税")
                .replace("5", "虚开增值税专用发票或者虚开用于骗取出口退税、抵扣税款的其他发票")
                .replace("6", "虚开普通发票")
                .replace("7", "私自印制、伪造、变造发票，非法制造发票防伪专用品，伪造发票监制章")
                .replace(
                    "9",
                    "具有偷 税、逃避 追缴欠税、骗 取出口退税、抗 税、虚开发票等行为，经税务机关检查确认走逃（失联）",
                )
                .replace("8", "其他")
            )
        item.province = self.province
        year = re.findall(r"((?:20|19)\d{2})[-.年 /]", item.illegal_facts)
        if year:
            item.year = year[-1]
        yield item


if __name__ == "__main__":

    from scrapy import cmdline

    cmdline.execute(argv=["scrapy", "crawl", "chongqing_illegal"])
